import os
import json

def generate_media_user_code():
    # 创建输出目录
    output_dir = 'c:\\Users\\Administrator\\RuoYi-Vue01\\generated_code'
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 标签类别信息
    label_categories = [
        {
            "name": "电视消费水平",
            "key": "tv_fee_level",
            "labels": ["电视超低消费", "电视低消费", "电视中等消费", "电视高消费"]
        },
        {
            "name": "宽带消费水平",
            "key": "broadband_fee_level",
            "labels": ["宽带低消费", "宽带中消费", "宽带高消费"]
        },
        {
            "name": "用户是否挽留",
            "key": "retention_status",
            "labels": ["挽留用户", "非挽留用户"]
        },
        {
            "name": "业务品牌",
            "key": "business_brand",
            "labels": ["互动电视", "数字电视", "甜果电视", "珠江宽频"]
        },
        {
            "name": "电视入网程度",
            "key": "tv_tenure_level",
            "labels": ["老用户", "中等用户", "新用户"]
        },
        {
            "name": "宽带入网程度",
            "key": "broadband_tenure_level",
            "labels": ["老用户", "中等用户", "新用户"]
        },
        {
            "name": "费用类型",
            "key": "fee_type",
            "labels": ["数字电视基本费", "互动基本费", "珠江宽频", "高清节目费"]
        }
    ]
    
    # 1. 生成前端Vue组件 - 广电用户列表
    generate_vue_component(output_dir, label_categories)
    
    # 2. 生成后端Controller
    generate_controller(output_dir)
    
    # 3. 生成后端Service
    generate_service(output_dir)
    
    # 4. 生成实体类
    generate_entity(output_dir)
    
    # 5. 生成菜单SQL
    generate_menu_sql(output_dir)
    
    print("\n代码生成完成！所有文件保存在: " + output_dir)

def generate_vue_component(output_dir, label_categories):
    vue_file = os.path.join(output_dir, 'MediaUserList.vue')
    
    # 生成过滤器选项代码
    filter_options = ''
    for category in label_categories:
        filter_options += f'''        <el-form-item label="{category['name']}">
          <el-select v-model="queryParams.{category['key']}" placeholder="请选择{category['name']}">
            <el-option label="全部" value=""></el-option>
'''
        for label in category['labels']:
            filter_options += f'''            <el-option label="{label}" value="{label}"></el-option>
'''
        filter_options += '''          </el-select>
        </el-form-item>
'''
    
    content = f'''
<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-loading="loading" label-width="100px">
      <el-form-item label="终端编号" prop="terminalNo">
        <el-input
          v-model="queryParams.terminalNo"
          placeholder="请输入终端编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户编号" prop="phoneNo">
        <el-input
          v-model="queryParams.phoneNo"
          placeholder="请输入用户编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="smName">
        <el-input
          v-model="queryParams.smName"
          placeholder="请输入品牌名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户标签" prop="userLabel">
        <el-select v-model="queryParams.userLabel" placeholder="请选择用户标签">
          <el-option label="全部" value=""></el-option>
          <el-option label="新用户" value="新用户"></el-option>
          <el-option label="潜在流失用户" value="潜在流失用户"></el-option>
          <el-option label="一般用户" value="一般用户"></el-option>
          <el-option label="忠诚用户" value="忠诚用户"></el-option>
          <el-option label="高价值用户" value="高价值用户"></el-option>
        </el-select>
      </el-form-item>
{filter_options}
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="终端编号" prop="terminalNo" align="center" />
      <el-table-column label="用户编号" prop="phoneNo" align="center" />
      <el-table-column label="品牌名称" prop="smName" align="center" />
      <el-table-column label="状态名称" prop="runName" align="center" />
      <el-table-column label="用户等级" prop="ownerName" align="center" />
      <el-table-column label="用户标签" prop="userLabel" align="center" />
      <el-table-column label="标签类型" prop="labelType" align="center" />
      <el-table-column label="开户时间" prop="openTime" align="center" />
      <el-table-column label="地址" prop="addressoj" align="center" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['media:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['media:user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/media/user"

export default {
  name: "MediaUserList",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户列表
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        terminalNo: undefined,
        phoneNo: undefined,
        smName: undefined,
        userLabel: undefined,
'''
    
    # 添加7个标签过滤参数
    for category in label_categories:
        content += "        " + category['key'] + ": undefined,\n"
    
    content += '''      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>
'''
    
    with open(vue_file, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("已生成前端Vue组件: " + vue_file)

def generate_controller(output_dir):
    controller_file = os.path.join(output_dir, 'MediaUserController.java')
    content = '''
package com.ruoyi.web.controller.media;

import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.media.domain.MediaUser;
import com.ruoyi.media.service.IMediaUserService;

/**
 * 广电用户Controller
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
@RestController
@RequestMapping("/media/user")
public class MediaUserController extends BaseController
{
    @Autowired
    private IMediaUserService mediaUserService;

    /**
     * 查询广电用户列表
     */
    @PreAuthorize("@ss.hasPermi('media:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(MediaUser mediaUser)
    {
        startPage();
        List<MediaUser> list = mediaUserService.selectMediaUserList(mediaUser);
        return getDataTable(list);
    }

    /**
     * 获取广电用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('media:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mediaUserService.selectMediaUserById(id));
    }

    /**
     * 新增广电用户
     */
    @PreAuthorize("@ss.hasPermi('media:user:add')")
    @Log(title = "广电用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MediaUser mediaUser)
    {
        return toAjax(mediaUserService.insertMediaUser(mediaUser));
    }

    /**
     * 修改广电用户
     */
    @PreAuthorize("@ss.hasPermi('media:user:edit')")
    @Log(title = "广电用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MediaUser mediaUser)
    {
        return toAjax(mediaUserService.updateMediaUser(mediaUser));
    }

    /**
     * 删除广电用户
     */
    @PreAuthorize("@ss.hasPermi('media:user:remove')")
    @Log(title = "广电用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mediaUserService.deleteMediaUserByIds(ids));
    }
}
'''
    
    with open(controller_file, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("已生成后端Controller: " + controller_file)

def generate_service(output_dir):
    service_file = os.path.join(output_dir, 'IMediaUserService.java')
    content = '''
package com.ruoyi.media.service;

import java.util.List;
import com.ruoyi.media.domain.MediaUser;

/**
 * 广电用户Service接口
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
public interface IMediaUserService
{
    /**
     * 查询广电用户列表
     * 
     * @param mediaUser 广电用户
     * @return 广电用户集合
     */
    public List<MediaUser> selectMediaUserList(MediaUser mediaUser);

    /**
     * 查询广电用户
     * 
     * @param id 广电用户主键
     * @return 广电用户
     */
    public MediaUser selectMediaUserById(Long id);

    /**
     * 新增广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    public int insertMediaUser(MediaUser mediaUser);

    /**
     * 修改广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    public int updateMediaUser(MediaUser mediaUser);

    /**
     * 批量删除广电用户
     * 
     * @param ids 需要删除的广电用户主键集合
     * @return 结果
     */
    public int deleteMediaUserByIds(Long[] ids);

    /**
     * 删除广电用户信息
     * 
     * @param id 广电用户主键
     * @return 结果
     */
    public int deleteMediaUserById(Long id);
}
'''
    
    impl_file = os.path.join(output_dir, 'MediaUserServiceImpl.java')
    impl_content = '''
package com.ruoyi.media.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.media.mapper.MediaUserMapper;
import com.ruoyi.media.domain.MediaUser;
import com.ruoyi.media.service.IMediaUserService;

/**
 * 广电用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
@Service
public class MediaUserServiceImpl implements IMediaUserService
{
    @Autowired
    private MediaUserMapper mediaUserMapper;

    /**
     * 查询广电用户列表
     * 
     * @param mediaUser 广电用户
     * @return 广电用户
     */
    @Override
    public List<MediaUser> selectMediaUserList(MediaUser mediaUser)
    {
        return mediaUserMapper.selectMediaUserList(mediaUser);
    }

    /**
     * 查询广电用户
     * 
     * @param id 广电用户主键
     * @return 广电用户
     */
    @Override
    public MediaUser selectMediaUserById(Long id)
    {
        return mediaUserMapper.selectMediaUserById(id);
    }

    /**
     * 新增广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    @Override
    public int insertMediaUser(MediaUser mediaUser)
    {
        return mediaUserMapper.insertMediaUser(mediaUser);
    }

    /**
     * 修改广电用户
     * 
     * @param mediaUser 广电用户
     * @return 结果
     */
    @Override
    public int updateMediaUser(MediaUser mediaUser)
    {
        return mediaUserMapper.updateMediaUser(mediaUser);
    }

    /**
     * 批量删除广电用户
     * 
     * @param ids 需要删除的广电用户主键集合
     * @return 结果
     */
    @Override
    public int deleteMediaUserByIds(Long[] ids)
    {
        return mediaUserMapper.deleteMediaUserByIds(ids);
    }

    /**
     * 删除广电用户信息
     * 
     * @param id 广电用户主键
     * @return 结果
     */
    @Override
    public int deleteMediaUserById(Long id)
    {
        return mediaUserMapper.deleteMediaUserById(id);
    }
}
'''
    
    with open(service_file, 'w', encoding='utf-8') as f:
        f.write(content)
    with open(impl_file, 'w', encoding='utf-8') as f:
        f.write(impl_content)
    
    print("已生成后端Service: " + service_file)
    print("已生成后端Service实现: " + impl_file)

def generate_entity(output_dir):
    entity_file = os.path.join(output_dir, 'MediaUser.java')
    content = '''
package com.ruoyi.media.domain;

import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * 广电用户对象 media_user_wide_table
 * 
 * @author ruoyi
 * @date 2025-12-04
 */
public class MediaUser
{
    private static final long serialVersionUID = 1L;

    /** 主键ID */
    private Long id;

    /** 终端编号 */
    private String terminalNo;

    /** 用户编号 */
    private String phoneNo;

    /** 品牌名称 */
    private String smName;

    /** 状态名称 */
    private String runName;

    /** 品牌编号 */
    private String smCode;

    /** 用户等级名称 */
    private String ownerName;

    /** 用户等级编号 */
    private String ownerCode;

    /** 状态变更时间 */
    private String runTime;

    /** 完整地址 */
    private String addressoj;

    /** 街道或小区地址 */
    private String estateName;

    /** 开户时间 */
    private String openTime;

    /** 宽带是否生效 */
    private String force;

    /** 用户标签 */
    private String userLabel;

    /** 标签类型 */
    private String labelType;

    /** 新用户标签 */
    private Integer labelNewUser;

    /** 潜在流失用户标签 */
    private Integer labelPotentialChurn;

    /** 一般用户标签 */
    private Integer labelRegularUser;

    /** 忠诚用户标签 */
    private Integer labelLoyalUser;

    /** 高价值用户标签 */
    private Integer labelHighValue;

    /** 创建时间 */
    private Date createTime;

    /** 更新时间 */
    private Date updateTime;

    // 7个标签过滤字段
    private String tvFeeLevel;
    private String broadbandFeeLevel;
    private String retentionStatus;
    private String businessBrand;
    private String tvTenureLevel;
    private String broadbandTenureLevel;
    private String feeType;

    public void setId(Long id)
    {
        this.id = id;
    }

    public Long getId()
    {
        return id;
    }

    // getter和setter方法...
    
    @Override
    public String toString() {
        return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
            .append("id", getId())
            .append("terminalNo", getTerminalNo())
            .append("phoneNo", getPhoneNo())
            .toString();
    }

    public String getTerminalNo() {
        return terminalNo;
    }

    public void setTerminalNo(String terminalNo) {
        this.terminalNo = terminalNo;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    public String getSmName() {
        return smName;
    }

    public void setSmName(String smName) {
        this.smName = smName;
    }

    public String getUserLabel() {
        return userLabel;
    }

    public void setUserLabel(String userLabel) {
        this.userLabel = userLabel;
    }
    
    // 其他getter和setter方法省略...
}
'''
    
    with open(entity_file, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("已生成实体类: " + entity_file)

def generate_menu_sql(output_dir):
    sql_file = os.path.join(output_dir, 'media_user_menu.sql')
    content = '''-- 广电用户管理菜单SQL
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20000, '广电用户管理', 10000, 1, 'media', 'media/index', 1, 0, 'C', '0', '0', '', 'el-icon-video-camera-solid', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '广电用户管理模块');

-- 广电用户列表菜单
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20001, '用户列表', 20000, 1, 'user', 'media/user/index', 1, 0, 'C', '0', '0', 'media:user:list', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '广电用户列表');

-- 新增按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20002, '新增用户', 20001, 2, '#', '', 0, 0, 'F', '0', '0', 'media:user:add', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');

-- 修改按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20003, '修改用户', 20001, 3, '#', '', 0, 0, 'F', '0', '0', 'media:user:edit', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');

-- 删除按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20004, '删除用户', 20001, 4, '#', '', 0, 0, 'F', '0', '0', 'media:user:remove', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');

-- 导出按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
VALUES (20005, '导出用户', 20001, 5, '#', '', 0, 0, 'F', '0', '0', 'media:user:export', '', 'admin', CURRENT_TIMESTAMP, 'admin', CURRENT_TIMESTAMP, '');
'''
    
    with open(sql_file, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("已生成菜单SQL: " + sql_file)

if __name__ == "__main__":
    generate_media_user_code()